package com.spider.demo6_lock;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {
    private String cardId;//卡号
    private double money;//余额
    private final Lock lock =new ReentrantLock();

    //小明和小红都到这里来取钱
    public void drawMoney(double  money) {
        //拿到当前是谁来取钱
        String name = Thread.currentThread().getName();
        //判断余额是否充足
        lock.lock();
        try {
            if (this.money >= money) {
                //余额充足
                System.out.println(name + "取钱成功，取钱金额为：" + money);
                this.money -= money;
                System.out.println(name + "取钱成功，余额为：" + this.money);

            }
            else {
                //余额不足
                System.out.println(name + "取钱失败，余额不足");
            }
        } finally {
            lock.unlock();//释放锁
        }
    }
}
